'use strict';
const Service = require('egg').Service;

class UserService extends Service {
  async findAll() {
    return  this.ctx.model.User.find({});
  }
  async register(opt){
    opt.level  = 1;
    opt.type = 1;
    opt.state = 0;
    //初始化强制一些参数
    let res = await this.ctx.model.User.findOne({"tel":opt.tel});
    if(res){
      return Promise.reject(this.app.resCode.repetition);
    }else{
      var user = new this.ctx.model.User(opt);
      return user.save();
    }
  }
  async login(opt){
    const {ctx,app} = this;
    let userInfo =  await ctx.model.User.findOne({"tel":opt.tel});
    if(!userInfo){
      return Promise.reject(app.resCode.nonexist);
    }else{
      var matchr = await userInfo.comparePasswordPromise(opt.password);
      if(matchr){
        userInfo = userInfo.toJSON();
        userInfo["password"] = null;
        delete userInfo["password"];
        return Promise.resolve(userInfo);
      }else{
        return Promise.reject(app.resCode.login);
      }
    }
  }
  async findOne(id){
    return this.ctx.model.User.findOne({"_id":id});
  }
  async update(id,opt){
    return this.ctx.model.User.updateOne({"_id":id},{"$set":opt});
  }
}

module.exports = UserService;

